package com.base;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.sql.DataSource;

import com.base.Config;
import com.utils.StringTool;

public class DBCPoolingListener implements ServletContextListener {

	public static ServletContextEvent sce = null;
	public static DataSource datasource = null;
	public static int pooledCount = 0;
	public static 	int nonPooledCount = 0;
	
	public void contextDestroyed(ServletContextEvent arg0) {
	}

	public void contextInitialized(ServletContextEvent scev) {
		try {
			System.out.println("DBCPoolingListener::contextInitialized");
			// Obtain our environment naming context
			// Look up our data source
			String poolName = Config.getStringProperty("poolName", "", false);
			System.out.println(poolName);
			if (StringTool.isEmptyOrNul(poolName)) return;
			Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			String[] arrPoolName = poolName.split(",");
			for (int i = 0; i < arrPoolName.length; i++) {
				String poolNameItem = arrPoolName[i];
				DataSource ds = (DataSource) new InitialContext().lookup("java:comp/env/"+poolNameItem);
				scev.getServletContext().setAttribute(poolNameItem, ds);
			}
			sce = scev;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static synchronized Connection getConnection(String poolName)
			throws SQLException {
			datasource = (DataSource) sce.getServletContext().getAttribute(poolName);
			
			// Allocate and use a connection from the pool
			return datasource.getConnection();
	}

}
